//
//  LoginViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 17/5/9.
//  Copyright © 2017年 Li Xiangyang. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController ,UITextFieldDelegate{

    @IBOutlet var userName: UITextField!
    @IBOutlet var password: UITextField!
    @IBOutlet var serverAddr: UITextField!
    @IBOutlet var loginButton: UIButton!
    @IBOutlet var ipLabel: UILabel!
    
    @IBOutlet var twIndicator: UIActivityIndicatorView!
    static var currentUser: TwERPUser?
    static var gdCategory: [String] = [""]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.preferredContentSize = CGSize(width: 400, height: 320)
        self.serverAddr.isHidden = true
        self.password.isSecureTextEntry = true
        self.serverAddr.text = UserDefaults.standard.string(forKey: "TWERPHostForMobile")
        
        ipLabel.isHidden = true
        twIndicator.isHidden = true
        
        serverAddr.delegate = self
        
        if LoginViewController.currentUser != nil {
            self.loginButton.setTitle("注销", for: UIControlState())
            self.userName.text = LoginViewController.currentUser?.userName
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func login(_ sender: AnyObject) {
        
        
        if loginButton.currentTitle == "注销" {
            LoginViewController.currentUser = nil
             self.userName.text = ""
            loginButton.setTitle("登录", for: UIControlState())
            return
        }
        
        if loginButton.currentTitle == "登录" {
            
            if !TwERPJsonAgent.isServerReachable() {
               let alert =  UIAlertController(title: "提示", message: "网络连接不正常，请检查！", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
                self.present(alert, animated: true){}
                return
            }

            twIndicator.startAnimating()
            twIndicator.isHidden = false
           
            DispatchQueue.global(qos: .userInitiated).async {
                let cuser: TwERPUser? = TwERPUser.loginUser(self.userName.text, withPassword: self.password.text)
            
                DispatchQueue.main.async {
                    self.twIndicator.isHidden = true
                    self.twIndicator.stopAnimating()

                    if cuser == nil {
                        let alert =  UIAlertController(title: "提示", message: "登录不成功，请检查网络连接或用户名口令是否正确！", preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
                        self.present(alert, animated: true){print("hello")}
                       
                    } else {
                        self.loginButton.setTitle("注销", for: UIControlState())
                        LoginViewController.currentUser = cuser
                        LoginViewController.gdCategory = TwERPJsonAgent.getCategoryOfGd() as! [String]
                        TwERPJsonAgent.setUserId((cuser?.entityId)!)
                        self.dismiss(animated: true, completion: nil)
                    }
                    
                }
            }
            
            return
        }

        

    }
    @IBAction func setServer(_ sender: AnyObject) {
        
        self.ipLabel.isHidden =  !self.ipLabel.isHidden;
        self.serverAddr.isHidden =  !self.serverAddr.isHidden;
    }
 
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
       
        TwERPJsonAgent.setHost(textField.text)
        UserDefaults.standard.set(textField.text, forKey: "TWERPHostForMobile")
        
 
    }
}
